package level

import (
	"context"
	"strings"

	"mall/common/errorx"
	"mall/common/jwtx"
	"mall/common/moneyx"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateMemberLevelLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateMemberLevelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMemberLevelLogic {
	return &UpdateMemberLevelLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateMemberLevelLogic) UpdateMemberLevel(req *types.UpdateMemberLevelReq) (resp *types.UpdateMemberLevelResp, err error) {
	if req.Id == 0 {
		return nil, errorx.Error(errorx.ERROR_MEMBER_LEVEL_ID_REQUIRED, "")
	}

	name := strings.TrimSpace(req.Name)
	if len(name) == 0 {
		return nil, errorx.Error(errorx.ERROR_MEMBER_LEVEL_NAME_REQUIRED, "")
	}

	adminId, _ := jwtx.GetUserId(l.ctx)

	var (
		withMemberPrice int32
		withPromotion   int32
		withFreeFreight int32
		withComment     int32
		withSignIn      int32
		withBirthday    int32
		isDefault       int32
	)
	if req.WithMemberPrice {
		withMemberPrice = 1
	}
	if req.WithPromotion {
		withPromotion = 1
	}
	if req.WithFreeFreight {
		withFreeFreight = 1
	}
	if req.WithComment {
		withComment = 1
	}
	if req.WithSignIn {
		withSignIn = 1
	}
	if req.WithBirthday {
		withBirthday = 1
	}
	if req.IsDefault {
		isDefault = 1
	}
	freeFreight, err := moneyx.ParseAmount(req.FreeFreightAmount)
	if err != nil {
		return
	}

	_, err = l.svcCtx.BackendRpc.UpdateMemberLevel(l.ctx, &backendclient.UpdateMemberLevelReq{
		Id:                 req.Id,
		Name:               name,
		Slug:               strings.TrimSpace(req.Slug),
		Desc:               req.Desc,
		MediaId:            req.MediaId,
		MediaUrl:           req.MediaUrl,
		Integral:           req.Integral,
		WithMemberPrice:    withMemberPrice,
		WithPromotion:      withPromotion,
		WithFreeFreight:    withFreeFreight,
		WithComment:        withComment,
		WithSignIn:         withSignIn,
		WithBirthday:       withBirthday,
		FreeFreight:        int32(freeFreight),
		IntegralForComment: req.IntegralForComment,
		TaskCount:          req.TaskCount,
		IsDefault:          isDefault,
		UpdatedBy:          adminId,
	})
	if err != nil {
		return nil, err
	}

	return &types.UpdateMemberLevelResp{
		Status:  "ok",
		Message: "更新成功",
	}, nil
}
